package com.abel.ignite.impl;

import com.abel.ignite.DefaultIgniteService;
import com.abel.ignite.parser.DMLParser;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.List;

/**
 * @author xiachao
 * @date 2019-04-29
 */
@Slf4j
@Component
public class DefaultIgniteServiceImpl implements DefaultIgniteService {

    @Resource
    private RepositoryManager repositoryManager;

    @Override
    public boolean insert(String cacheName, JSONObject json) {
        if(StringUtils.isEmpty(cacheName) || json == null){
            return false;
        }
        String sql = DMLParser.parseInsert(cacheName, json);
        return this.repositoryManager.insert(cacheName, sql);
    }

    @Override
    public boolean delete(String cacheName, String sql) {
        return this.repositoryManager.delete(cacheName, sql);
    }

    @Override
    public boolean update(String cacheName, String sql) {
        return this.repositoryManager.update(cacheName, sql);
    }

    @Override
    public boolean update(String cacheName, JSONObject json) {
        if(json == null || !json.containsKey("id")
                || !json.containsKey("ID")){
            log.error("id can not be empty for JSONObject");
        }
        String sql = DMLParser.parseUpdate(cacheName, json);
        return this.repositoryManager.update(cacheName, sql);
    }

    @Override
    public List<List<?>> query(String cacheName, String sql) {
        return this.repositoryManager.query(cacheName, sql);
    }

}
